using System;
using System.Collections.Generic;
using System.Text;

namespace DocLibApp
{
    public class doc_operation
    {
        /// <summary>
        /// Create new document record
        /// </summary>
        /// <param name="ht"></param>
        /// <returns></returns>
        public static string CreatNewDocument(System.Collections.Hashtable ht)
        {
            string res = "";

            try
            {
                //setup some default value
                ht["AUTHOR"] = FormMain.DocLib_CurrentUser;
                ht["DT_CREATE"] = SQLiteDB.DateTimeToString(System.DateTime.Now);
                ht["DT_UPDATE"] = SQLiteDB.DateTimeToString(System.DateTime.Now);

                FormMain.DocLib_QB.TableName = def.tb_doc;
                FormMain.DocLib_QB.Get_Insert(ht);
                FormMain.DocLib_QB.RunQuery();
            }
            catch (System.Exception ex)
            {
                res = ex.Message;
            }

            return res;
        }

        /// <summary>
        /// Retrieve Information about a Document Record
        /// </summary>
        /// <param name="doc_id">Document ID</param>
        /// <returns></returns>
        public static System.Collections.Hashtable GetDocumentInformation(string doc_id)
        {
            System.Collections.Hashtable ht = new System.Collections.Hashtable();

            System.Collections.Hashtable htWhere = new System.Collections.Hashtable();
            htWhere["DOC_ID"] = doc_id;
            FormMain.DocLib_QB.TableName = def.tb_doc;
            FormMain.DocLib_QB.Get_Select(htWhere);

            ht = FormMain.DocLib_QB.GetDataOneRowInHash();

            return ht;
        }

        /// <summary>
        /// Get original file name information for a document record
        /// </summary>
        /// <param name="doc_id"></param>
        /// <returns></returns>
        public static string GetOriginalFileName(string doc_id)
        {
            string orgfilename = "";

            orgfilename = FormMain.DocLib_SQLite.GetDataString("SELECT [ORIGINAL_FILENAME] FROM " + def.tb_doc + " WHERE [DOC_ID] = '" + doc_id + "'");

            return orgfilename;
        }

        /// <summary>
        /// Save changes to a document record in library
        /// </summary>
        /// <param name="doc_id"></param>
        /// <param name="ht"></param>
        /// <returns></returns>
        public static string SaveDocumentInformation(string doc_id, System.Collections.Hashtable ht)
        {
            string res = "";
            try
            {
                System.Collections.Hashtable ht_Where = new System.Collections.Hashtable();
                ht_Where["DOC_ID"] = doc_id;

                //setup some default
                ht["DT_UPDATE"] = SQLiteDB.DateTimeToString(System.DateTime.Now);

                FormMain.DocLib_QB.TableName = def.tb_doc;
                FormMain.DocLib_QB.Get_Update(ht, ht_Where);
                FormMain.DocLib_QB.RunQuery();

                //Record e-sig & audit trail here
                GenerateAuditTrailForDocument(doc_id, "UPDATE", FormMain.DocLib_CurrentUser);
            }
            catch (System.Exception ex)
            {
                res = ex.Message;
            }

            return res;
        }

        /// <summary>
        /// Apply batch changes to a list of documents
        /// </summary>
        /// <param name="FileList">list of doc_id</param>
        /// <param name="ht">contains fields and values</param>
        /// <returns></returns>
        public static string ApplyBatchChangeToDocuments(List<string> FileList, System.Collections.Hashtable ht)
        {
            string res = "";

            FormMain.DocLib_QB.TableName = def.tb_doc;
            FormMain.DocLib_QB.Get_Update(ht, "DOC_ID", FileList);
            FormMain.DocLib_QB.RunQuery();

            //apply update audit trail
            foreach (string doc_id in FileList)
            {
                GenerateAuditTrailForDocument(doc_id, "UPDATE", FormMain.DocLib_CurrentUser);
            }

            return res;
        }

        public static System.Collections.ArrayList GetDocumentAuditTrail(string doc_id)
        {
            System.Collections.Hashtable htWhere = new System.Collections.Hashtable();
            htWhere["DOC_ID"] = doc_id;

            FormMain.DocLib_QB.TableName = def.tb_doc_audit;
            FormMain.DocLib_QB.Get_Select(htWhere);

            System.Collections.ArrayList alist = FormMain.DocLib_SQLite.GetRowsWithDataReader_IncludeColumnDescription(FormMain.DocLib_QB.SQL, def.tb_doc_audit, "EVENT_ID");

            //double check hash to make sure they are valid

            return alist;
        }

        /// <summary>
        /// Generate audit trail info for document
        /// tested
        /// </summary>
        /// <param name="doc_id"></param>
        /// <param name="action"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static bool GenerateAuditTrailForDocument(string doc_id, string action, string user)
        {
            System.Collections.Hashtable ht = new System.Collections.Hashtable();
            ht["DOC_ID"] = doc_id;
            ht["ACTION"] = action;
            ht["SIGN_USER"] = user;
            ht["DT_EVENT"] = SQLiteDB.DateTimeToString(System.DateTime.Now);

            return  doc_security.CreateAuditTrail(ht);
        }

        /// <summary>
        /// Launch the 1st file in the zip file for document archive
        /// </summary>
        /// <param name="doc_id"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ViewDocument(string doc_id, string path)
        {
            string filename = System.IO.Path.Combine(path, doc_id + ".zip");

            string docfilename = FormMain.DocLib_SQLite.GetDataString("select [ORIGINAL_FILENAME] FROM " + def.tb_doc + " WHERE [DOC_ID] = '" + doc_id + "'");

            if (System.IO.File.Exists(filename))
            {
                string temp_path = System.IO.Path.GetTempPath();

                util.ExtractFileFromZip(filename, docfilename, temp_path, def.ZipPassword);

                string extractFilename = System.IO.Path.Combine(temp_path, docfilename);

                if (System.IO.File.Exists(extractFilename))
                {
                    util.RunFileWaitForExit(extractFilename);

                    System.IO.File.Delete(extractFilename);
                }
            }
            else
            {
                return "Document file does not exist.";
            }

            return "";
        }

        public static string SaveDocumentCopy(string doc_id, string path, string originalfilename, string saveToFileName)
        {
            string zipfilename = System.IO.Path.Combine(path, doc_id + ".zip");
            string tmp = System.IO.Path.GetTempPath();

            if (System.IO.File.Exists(zipfilename))
            {
                util.ExtractFileFromZip(zipfilename, originalfilename, tmp, def.ZipPassword);

                string extracFilename = System.IO.Path.Combine(tmp, originalfilename);

                if (System.IO.File.Exists(extracFilename))
                {
                    System.IO.File.Copy(extracFilename, saveToFileName);

                    System.IO.File.Delete(extracFilename);
                }
            }
            else
            {
                return "Document zip file does not exist.";
            }

            return "";
        }

        public static System.Collections.ArrayList SearchDocument(System.Collections.Hashtable ht_Criteria)
        {
            FormMain.DocLib_QB.TableName = def.tb_doc;
            FormMain.DocLib_QB.Get_Select(ht_Criteria);
            System.Collections.ArrayList alist = FormMain.DocLib_SQLite.GetRowsWithDataReader_IncludeColumnDescription(FormMain.DocLib_QB.SQL, def.tb_doc, "DOC_ID");

            return alist;
        }

        /// <summary>
        /// Delete Document Record (optionally remove the document zip file
        /// </summary>
        /// <param name="doc_id"></param>
        /// <param name="bDeleteDocFile"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string DeleteDocument(string doc_id, bool bDeleteDocFile, string path)
        {
            try
            {
                System.Collections.Hashtable ht = new System.Collections.Hashtable();
                ht["DOC_ID"] = doc_id;

                FormMain.DocLib_QB.TableName = def.tb_doc;
                FormMain.DocLib_QB.Get_Delete(ht);
                FormMain.DocLib_QB.RunQuery();

                //delete e-sig * audit trail
                doc_security.DeleteAuditTrail(doc_id);

                if (bDeleteDocFile)
                {
                    string filename = System.IO.Path.Combine(path, doc_id + ".zip");
                    if (System.IO.File.Exists(filename))
                        System.IO.File.Delete(filename);
                    else
                        return "Document zip file does not exist.";
                }
            }
            catch (System.Exception ex)
            {
                return ex.Message;
            }

            return "Document is deleted successfully.";
        }
    }
}
